package com.flyu.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取要下载文件的地址
        String realPath = "E:\\JavaProjects\\src\\main\\java\\com\\flyu\\javaweb-01-maven\\response\\target\\classes\\兵马俑.jpg";
        System.out.println("下载文件的路径："+realPath);
        // 2. 下载的文件名
        String filename = realPath.substring(realPath.lastIndexOf("\\")+1);
        // 3. 设置想办法让浏览器支持（Content-Disposition）下载我们需要的东西
        // 中文文件需要URLEncoder.encode编码，否则可能乱码
        resp.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(filename, "utf-8"));
        // 4. 获取文件下载的输入流
        FileInputStream is = new FileInputStream(realPath);
        // 5. 创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        // 6. 获取OutputStream对象
        ServletOutputStream os = resp.getOutputStream();
        // 7. 将FileOutputStream流写入buffer缓冲区，使用OutputStream将缓冲区中的数据输出到客户端
        while ((len=is.read(buffer))!=-1){
            os.write(buffer, 0, len);
        }
        is.close();
        os.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
